package com.example.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.reggie.common.R;
import com.example.reggie.entity.ShoppingCart;
import com.example.reggie.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.One;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@RestController
//http://localhost:8080/shoppingCart/add
@RequestMapping("/shoppingCart")
public class ShoppingCartController {
  @Autowired
  private ShoppingCartService shoppingCartService;
  @PostMapping("/add")
    public R<ShoppingCart> addShoping(@RequestBody ShoppingCart shoppingCart, HttpSession session){
      log.info("加入购物车");
    Long userId =(Long) session.getAttribute("user");
    shoppingCart.setUserId(userId);

    LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper.eq(ShoppingCart::getUserId,userId);
    Long dishId = shoppingCart.getDishId();
    if ( dishId!= null) {
      queryWrapper.eq(ShoppingCart::getDishId,dishId);

    }else {
      queryWrapper.eq(ShoppingCart::getSetmealId,shoppingCart.getSetmealId());
    }

    ShoppingCart one = shoppingCartService.getOne(queryWrapper);
    if(one!=null){
      Integer number = one.getNumber();
      number++;
      one.setNumber(number);
      shoppingCartService.updateById(one);
    }else {
      shoppingCart.setCreateTime(LocalDateTime.now());
      shoppingCartService.save(shoppingCart);
      one=shoppingCart;
    }

    return R.success(one);
  }


  @GetMapping("/list")
  public  R<List<ShoppingCart>>  shoppinglist(HttpSession httpSession)
  {
    Long userId = (Long) httpSession.getAttribute("user");
    LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper.eq(ShoppingCart::getUserId,userId)
            .orderByDesc(ShoppingCart::getCreateTime);
    List<ShoppingCart> shoppingCartList = shoppingCartService.list(queryWrapper);
    return R.success(shoppingCartList);
  }

  @DeleteMapping("/clean")
  public   R<String> shoppingClean(HttpSession httpSession)
  {
    LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper.eq(ShoppingCart::getUserId,(Long)httpSession.getAttribute("user"));
    shoppingCartService.remove(queryWrapper);
    return  R.success("清空成功");

  }
}
